import React from "react";
import { Tag, Space } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { closeTab, setCurrentMenu } from "../../store/reducers/tab";
import "./index.css";
import { useLocation,  useNavigate } from "react-router-dom";

const CommonTag = () => {
  const tabList = useSelector((state) => state.tab.tabList);
  const currentMenu = useSelector((state) => state.tab.currentMenu);
  console.log("currentMenu", currentMenu);
  const action = useLocation();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  // 关闭tag
  const handleClose = (tag, index) => {
    let length = tabList.length - 1;
    dispatch(closeTab(tag));
    // 关闭的不是当前路由
    if (tag.path !== action.pathname) {
      return;
    }

    if (index === length) {
      //设置当前数据
      const curData = tabList[index - 1];
      dispatch(setCurrentMenu(curData));
      navigate(curData.path);
    } else {
      if (tabList.length > 1) {
        const nextData = tabList[index + 1];
        dispatch(setCurrentMenu(nextData));
        navigate(nextData.path);
      }
    }
  };
  // 点击tag
  const handleChange = (tag) => {
    dispatch(setCurrentMenu(tag));
    navigate(tag.path);
  };
  const setTag = (flag, item, index) => {
    return flag ? (
      <Tag
        color="#55acee"
        colorIcon
        onClose={() => handleClose(item, index)}
        closeIcon
        key={item.name}
      >
        {item.label}
      </Tag>
    ) : (
      <Tag onClick={() => handleChange(item, index)} key={item.name}>
        {item.label}
      </Tag>
    );
  };
  return (
    <Space className="common-tag" size={[0, 8]} wrap>
      {currentMenu.name &&
        tabList.map((item, index) => {
          return setTag(item.path == currentMenu.path, item, index);
        })}
    </Space>
  );
};

export default CommonTag;
